package cn.maihe.elg.operation.supports.sms;

import cn.maihe.elg.operation.config.AliyunSmsConfig;
import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description 阿里云的短信服务
 * @Author WJH
 * @Date 2021/06/18
 */
@Service
@Slf4j
public class AliyunSmsService {

    private Client client;
    private AliyunSmsConfig smsConfig;

    public AliyunSmsService(AliyunSmsConfig smsConfig) {

        Assert.hasText(smsConfig.getAccessKeyId(), "aliyun.sms.accessKeyId未配置");
        Assert.hasText(smsConfig.getAccessKeySecret(), "aliyun.sms.accessKeySecret未配置");
        Assert.hasText(smsConfig.getEndpoint(), "aliyun.sms.endpoint未配置");
        Assert.hasText(smsConfig.getSignName(), "aliyun.sms.signName未配置");
        Assert.hasText(smsConfig.getAuthCodeTemplateCode(), "aliyun.sms.authCodeTemplateCode未配置");
        Assert.hasText(smsConfig.getWaitPayTemplateCode(), "aliyun.sms.WaitPayTemplateCode未配置");
        Assert.hasText(smsConfig.getPayWarningTemplateCode(), "aliyun.sms.PayWarningTemplateCode未配置");
        Assert.hasText(smsConfig.getConfirmPayTemplateCode(), "aliyun.sms.ConfirmPayTemplateCode未配置");
        Assert.hasText(smsConfig.getGuaranteeSuccessTemplateCode(), "aliyun.sms.GuaranteeSuccessTemplateCode未配置");

        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(smsConfig.getAccessKeyId())
                // 您的AccessKey Secret
                .setAccessKeySecret(smsConfig.getAccessKeySecret())
                // 访问的域名
                .setEndpoint(smsConfig.getEndpoint());
        try {
            this.client = new Client(config);
            this.smsConfig = smsConfig;
        } catch (Exception e) {
            throw new RuntimeException("阿里云短信服务客户端初始化异常:" + e.getMessage(), e);
        }
    }

    /**
     * 短信模板内容：登录验证码为{},请勿将验证码泄露给他人，有效期{}分钟
     */
    public void sendAuthCodeSms(String targetMobile, String authCode, String minute) {
        Map<String, String> params = new HashMap<>(8);
        params.put("authCode", authCode);
        params.put("minute", minute);
        sendSms(targetMobile, smsConfig.getAuthCodeTemplateCode(), JSON.toJSONString(params));
    }

    /**
     * 待支付短信模板内容：项目标段名称：{},已为您报价保费金额{}元，请尽快打款支付，以免影响开函进度
     */
    public void sendWaitPaySms(String targetMobile, String sectionName, String guaranteeFeeAmt) {
        Map<String, String> params = new HashMap<>(8);
        params.put("sectionName", sectionName);
        params.put("guaranteeFeeAmt", guaranteeFeeAmt);
        sendSms(targetMobile, smsConfig.getWaitPayTemplateCode(), JSON.toJSONString(params));
    }

    /**
     * 支付截止日期提醒短信模板内容：项目标段名称：{},已为您报价保费金额{}元，支付截止时间为：{}，请尽快打款支付
     */
    public void sendPayWarningSms(String targetMobile, String sectionName, String guaranteeFeeAmt, String endDatetime) {
        Map<String, String> params = new HashMap<>(8);
        params.put("sectionName", sectionName);
        params.put("guaranteeFeeAmt", guaranteeFeeAmt);
        params.put("endDatetime", endDatetime);
        sendSms(targetMobile, smsConfig.getPayWarningTemplateCode(), JSON.toJSONString(params));
    }

    /**
     * 支付确认短信模板内容：项目标段名称：{},已支付确认到账保费金额{}元
     */
    public void sendConfirmPaySms(String targetMobile, String sectionName, String guaranteeFeeAmt) {
        Map<String, String> params = new HashMap<>(8);
        params.put("sectionName", sectionName);
        params.put("guaranteeFeeAmt", guaranteeFeeAmt);
        sendSms(targetMobile, smsConfig.getConfirmPayTemplateCode(), JSON.toJSONString(params));
    }

    /**
     * 开函成功短信模板内容：项目标段名称：{},已成功开函,对应的保函编号为{}
     */
    public void sendGuaranteeSuccessSms(String targetMobile, String sectionName, String guaranteeCode) {
        Map<String, String> params = new HashMap<>(8);
        params.put("sectionName", sectionName);
        params.put("guaranteeCode", guaranteeCode);
        sendSms(targetMobile, smsConfig.getGuaranteeSuccessTemplateCode(), JSON.toJSONString(params));
    }

    /**
     * 若异常则 保存发送内容，间隔多久重新发送，重试几次均失败则丢弃，其他则标识发送成功
     *
     * @param targetMobile
     * @param templateCode
     * @param jsonString
     */
    private void sendSms(String targetMobile, String templateCode, String jsonString) {
        //短信模板暂未申请，暂不发送
        if(1==1){
            log.error("短信模板暂未申请，暂不发送。【"+jsonString+"】");
            return ;
        }
        SendSmsRequest request = new SendSmsRequest().setPhoneNumbers(targetMobile)
                .setSignName(smsConfig.getSignName()).setTemplateCode(templateCode)
                .setTemplateParam(jsonString);
        try {
            SendSmsResponse response = this.client.sendSms(request);
            if (response != null && response.getBody() != null) {
                SendSmsResponseBody body = response.getBody();
                if (!"OK".equals(body.getCode())) {
                    throw new RuntimeException("短信发送失败:" + body.getCode() + ":" + body.getMessage());
                }
            }
            throw new RuntimeException("短信发送失败:响应报文为空");
        } catch (Exception e) {
            throw new RuntimeException("短信发送异常:" + e.getMessage(), e);
        }
    }


}
